package com.ebrothers.isns.common;

import java.util.HashMap;
import java.util.Map.Entry;

import com.ebrothers.isns.common.PrefsManager.Keys;

import android.content.Context;

public final class API {
	private static final String HTTP = "http://";
	private static final String WEBAPP_PATH = "/";
	// TODO change server ip
	private static final String DEFAULT_SERVER_IP = "isns1.s42.eatj.com";
	public static final String GOOGLE_MAPS_IP = "http://maps.google.com/maps/api/geocode/json?";
	private static String sServerIP = DEFAULT_SERVER_IP;

	public static final int NEW_QUESTION = 0;
	public static final int ANSWER_QUESTION = 1;
	public static final int LIST_QUESTIONS = 2;
	public static final int LIST_ANSWERS = 3;

	public static void setServerIP(Context context, String ip) {
		sServerIP = ip;
		final PrefsManager pm = PrefsManager.getInstance(context);
		pm.edit();
		pm.putString(Keys.SERVER_IP, ip);
		pm.commit();
	}

	public static String getServerIP(Context context) {
		final PrefsManager pm = PrefsManager.getInstance(context);
		sServerIP = pm.getString(Keys.SERVER_IP, DEFAULT_SERVER_IP);
		return sServerIP;
	}

	public static String getServerUrl(Context context) {
		final PrefsManager pm = PrefsManager.getInstance(context);
		sServerIP = pm.getString(Keys.SERVER_IP, DEFAULT_SERVER_IP);
		return HTTP + sServerIP + WEBAPP_PATH;
	}

	public static String getURL(int apiType, HashMap<String, String> params) {
		StringBuilder url = new StringBuilder();
		final String urlPrefix = HTTP + sServerIP + WEBAPP_PATH;
		url.append(urlPrefix);
		switch (apiType) {
		case NEW_QUESTION:
			url.append("NewQuestion");
			break;
		case ANSWER_QUESTION:
			url.append("AnswerQuestion");
			break;
		case LIST_QUESTIONS:
			url.append("ListQuestions");
			break;
		case LIST_ANSWERS:
			url.append("ListAnswers");
			break;
		default:
			break;
		}
		if (url != null && params != null) {
			url.append("?");
			for (Entry<String, String> entry : params.entrySet()) {
				url.append(entry.getKey()).append("=")
						.append(entry.getValue().replace(" ", "%20"))
						.append("&");
			}
		}
		return url.substring(0, url.length() - 1);
	}
}
